# 导入必要的库
import os
import openpyxl
import re
from docx import Document

# 生成合同文档并替换文本占位符的函数
def generate_contract(word_template, data_dict, output_folder):
    """
    生成合同文档并替换文本占位符。

    Args:
        word_template (str): 合同范本的文件路径.
        data_dict (dict): 包含占位符和相应替换值的字典.
        output_folder (str): 生成合同文档的输出文件夹路径.
    """
    doc = Document(word_template)

    # 遍历每个段落进行占位符替换
    for paragraph in doc.paragraphs:
        replaced_text = paragraph.text
        for key, value in data_dict.items():
            placeholder = "{" + key + "}"
            escaped_placeholder = re.escape(placeholder)  # 转义特殊字符
            if re.search(escaped_placeholder, replaced_text):
                replaced_text = re.sub(escaped_placeholder, str(value), replaced_text)
        paragraph.text = replaced_text

    base_filename = f"{data_dict['合同委托方_1']}"
    output_doc = os.path.join(output_folder, f"{base_filename}.docx")

    # 处理重复的文件名
    count = 1
    while os.path.exists(output_doc):
        count += 1
        output_doc = os.path.join(output_folder, f"{base_filename}_{count}.docx")

    doc.save(output_doc)

def main():
    word_template = "合同范本.docx"
    excel_file = "录入信息.xlsx"
    output_folder = os.path.dirname(os.path.abspath(__file__))  # 当前脚本所在目录

    # 加载 Excel 数据
    wb = openpyxl.load_workbook(excel_file)
    sheet = wb.active
    columns = [cell.value for cell in sheet[1]]
    rows = list(sheet.iter_rows(min_row=2, values_only=True))

    # 逐行生成合同文档
    for row_values in rows:
        data_dict = dict(zip(columns, row_values))
        generate_contract(word_template, data_dict, output_folder)  # 调用生成合同函数

    wb.close()

    print("批量生成 Word 文档完成。")

if __name__ == "__main__":
    main()
